package plugin.live.mongodb;

import java.lang.reflect.Field;
import java.util.List;

import com.cybermkd.mongo.kit.MongoQuery;

import net.vidageek.mirror.dsl.Mirror;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class MongoOom<T> {
	private MongoQuery query;

	private Class c;

	public MongoOom(Class c) {
		this.c = c;
		//需要每次都进行实例化,不然第二次查询会查询不到
//		query = new MongoQuery().use(c.getSimpleName());
	}
	
	/**
	 * 匹配字段条件
	 * @param obj
	 * @return
	 */
	public MongoQuery getQuery(T obj) {
		query = new MongoQuery().use(c.getSimpleName());
		List<Field> fs = new Mirror().on(obj.getClass()).reflectAll().fields();
		for (Field field : fs) {
			if (field.getModifiers() != 2) {// 不是private
				continue;
			}
			Object value = new Mirror().on(obj).get().field(field);
			if (value == null) {
				continue;
			}
			query.eq(field.getName(), value);
		}
		return query;
	}



	public boolean del(String id) {
		query = new MongoQuery().use(c.getSimpleName());
		return query.byId(id).deleteOne();
	}
	/**
	 * 删除匹配条件
	 * @param obj
	 * @return
	 */
	public long del(T obj) {
		query = this.getQuery(obj);//匹配查询条件
		return query.delete();
	}

	public boolean save(T obj) {
		query = new MongoQuery().use(c.getSimpleName());
		return query.set(obj).save();
	}

	public boolean update(T obj) {
		query = new MongoQuery().use(c.getSimpleName());
		String id = ((MongoBeanMy)obj).getId();
		if (query.byId(id).replace(obj) > 0) {
			return true;
		}
		return false;
	}
	public long update(T exist,T replaceBean) {
		return this.getQuery(exist).replace(replaceBean);
	}
	
	public boolean updateById(T obj) {
		query = new MongoQuery().use(c.getSimpleName());
		String id = ((MongoBeanMy) obj).getId();
		if (query.byId(id).replace(obj) > 0) {
			return true;
		}
		return false;
	}
	public boolean saveOrUpdate(T obj) {
		String id = ((MongoBeanMy)obj).getId();
		if(id == null || "".equals(id)) {
			return this.save(obj);
		}
		return this.update(obj);
	}

	public T findById(String id) {
		query = new MongoQuery().use(c.getSimpleName());
		return (T) query.byId(id).findOne(c);
	}
	
	public T findOne(T obj) {
		query = this.getQuery(obj);// 匹配查询条件
		return (T) query.findOne(c);
	}

	public List<T> findAll() {
		query = new MongoQuery().use(c.getSimpleName());
		return query.findAll(c);
	}

	/**
	 * 查询数据库
	 * 
	 * @param obj
	 */
	public List<T> find(T obj) {
		query = this.getQuery(obj);//匹配查询条件
		List<T> list = query.find(c);
		return list;
	}
	
	
}
